<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MainPage extends CI_Controller {
	
	function __construct() {
		parent::__construct();
		// used in the view
		$this->load->helper('url');		
	}
	
	public function index()	{
		
		set_time_limit(0);
					
		// echo "<pre>";
		// print_r(get_current_user());
		// echo "</pre>";
		
		// $logName = '';
		// $debugFileName = '';
			
		$environment = array(
			'EVO' => 'EVO',
			1 => 'TST 01',
			2 => 'TST 02'
		);
		
		// $logName = $this->session->flashdata('logName');
		// $debugFileName = $this->session->flashdata('debugFileName');
		
		
		$this->load->model('get_function');
		$currentFormatedDateTime = $this->get_function->getCurrentToNumberDateTime();
		$logName = 'log_'.$currentFormatedDateTime.'.html';
		$debugFileName = 'debugfile_'.$currentFormatedDateTime.'.txt';
		$outputFileName = 'output_'.$currentFormatedDateTime.'.xml';
		$reportFileName = 'report_'.$currentFormatedDateTime.'.html';
		$folderName = $currentFormatedDateTime;
		
		// print_r($logName);
		// echo '</br>';
		// print_r($debugFileName);
		
		$this->load->library('form');
		
		$this->form

		// if the form is submitted to the same url this can be omitted
		->open('mainPage')
		
		->fieldset('Uruchamianie polecenia')		
		// ->br()
		->text('command', 'Wprowadź zmienne', 'max_length[1000]', '', 'style=width:590px; font-size: 14px;, element_suffix=""')		// ->submit('Uruchom', 'run_prepared_command', '', '')	
		->button('Uruchom', 'run_prepared_command', '', '')
		// ->text('command', 'Wprowadź polecenie', 'required|max_length[255]', '', 'style=width:440px; font-size: 14px;, element_suffix=""')		
		->space()		
		// ->br()
		->text('command2', 'Wprowadź dowolne polecenie', 'max_length[1000]', '', 'style=width:590px; font-size: 14px;, element_suffix=""')
		->submit('Uruchom', 'run_any_prepared_command', '', '')	
		->br()
		// ->fieldset_close()
		->br()
		
		->fieldset()						->indent(112)
		->select('environment', $environment, 'Środowisko testowe', 'EVO', '', 'style=width:102px;')	
		// ->col(0)
		->indent(80)
		// ->br()	
		// ->indent(0)
		// ->label('Wprowadź idZamówienia', 'order_id', 'id="order_id_label" <!--style="width:auto; padding-left:20px; padding-right:10px;"-->', '')		// 
		// ->indent(0)
		->text('order_id', 'Wprowadź idZamówienia', 'max_length[15]|is_numeric', '', 'style=width:130px; font-size: 14px;, element_suffix=""')
		->submit('Uruchom', 'run_with_order_id', '', '')
		->br()			
		->indent(131)
		->text('personal_number', 'Wprowadź PESEL', 'max_length[11]|is_numeric', '', 'style=width:130px; font-size: 14px; , element_suffix=""')
		->submit('Uruchom', 'run_with_personal_number', '', '')		
		->html('<input type="hidden" id="log_name_hidden" name="log_name_hidden" value='.$logName.' />')		
		->html('<input type="hidden" id="debugfile_name_hidden" name="debugfile_name_hidden" value='.$debugFileName.' />')	
		->html('<input type="hidden" id="output_file_name_hidden" name="output_file_name_hidden" value='.$outputFileName.' />')		
		->html('<input type="hidden" id="report_file_name_hidden" name="report_file_name_hidden" value='.$reportFileName.' />')	
		->html('<input type="hidden" id="folder_name_hidden" name="folder_name_hidden" value='.$folderName.' />')
		->fieldset_close();

		// get the form output and write it to the $data array
		// this method automatically validates the form data
		$data['form'] = $this->form->get();
		
		//$commmand['command'] = shell_exec('ipconfig');
		
		
		if ($this->form->valid)
		{
			//$post = $this->form->get_post(TRUE);
			//print_r($post);	
				
			// print_r($_POST);
			// echo '</br>';
			
			// $this->load->model('get_function');
			
			$logName = $_POST['log_name_hidden'];
			$debugFileName = $_POST['debugfile_name_hidden'];
			$outputFileName = $_POST['output_file_name_hidden'];
			$reportFileName = $_POST['report_file_name_hidden'];
			$folderName = $_POST['folder_name_hidden'];
			// $userName = get_current_user();
			$userName = gethostbyaddr($_SERVER['REMOTE_ADDR']);
						
			$this->get_function->createFolder('logs/'.$folderName);
				
			foreach($_POST as $key => $value) {  
				// print_r($key); 
				// echo '</br>'; 
				// print_r($value);
				// echo '</br>';
				
				// echo 'run_with_personal_number: '.$_POST[0];
				// echo '</br>';	
		        if ($key != null) {
		        	// $runPreparedCommand = $_POST['run_prepared_command'];
					// $runWithPersonalNumber = $_POST['run_with_personal_number'];
					// $runWithOrderId = $_POST['run_with_order_id'];			
					switch ($key) {
						case 'run_prepared_command':		
							// $command = $_POST['command'];
							// $this->session->set_flashdata('logName', $logName);
							// $this->session->set_flashdata('debugFileName', $debugFileName);
							// // print_r('</br>key: run_prepared_command </br>');
							// $this->session->set_flashdata('command', $command);
							// // $this->session->set_flashdata('data', $data);
							// redirect('mainPage/run');
							$variables = $_POST['command']; //inserted variables
							$command = 'start "'.$logName.'" /MIN jybot --log logs//'.$folderName.'//'.$logName.' --output .//logs//'.$folderName.'//'.$outputFileName.'  --report .//logs//'
								.$folderName.'//'.$reportFileName.' --debugfile .//logs//'.$folderName.'//'.$debugFileName.' '.$variables.' C:\ROBOT\CyfrowyPolsat\CyfrowyPolsat\SOS.tsv 2>&1 &';
							// print_r('</br>key: run_any_prepared_command </br>');
							// print_r('</br>COMMAND: '.$command.'</br>');
				        	$this->get_function->addToLog('log.txt', $command, $userName);
							// $this->get_function->clearFile('debugfile.txt', 'logs/');
							// print_r('</br>COMMAND: '.$command.'</br>');							
							// $command = 'start "'.$logName.'" '.$command;
							// ob_start();
							shell_exec($command);				
							// ob_end_clean();
							redirect('');
				        	break;
						case 'run_any_prepared_command':
							$command = $_POST['command2'].' > logs//'.$folderName.'//'.$debugFileName;
							// print_r('</br>key: run_any_prepared_command </br>');
							// print_r('</br>COMMAND: '.$command.'</br>');
				        	$this->get_function->addToLog('log.txt', $command, $userName);
							// $this->get_function->clearFile('debugfile.txt', 'logs/');
							// print_r('</br>COMMAND: '.$command.'</br>');							
							// $command = 'start "'.$logName.'" '.$command;
							// ob_start();
							shell_exec($command);
							// $logName = 'xxx.html';
							
							// $pathToFile = 'logs/'.$logName;
							// while (!file_exists($pathToFile)) {
								// sleep(1);
							// }
// 							
							// shell_exec('TASKkill /FI "WINDOWTITLE eq '.$logName.'"');
							// shell_exec('TASKkill /FI "WINDOWTITLE eq cmd.exe"');
							
							// $task_completed = false;
							// while(!$task_completed) {
							    // if(connection_aborted() == 1) {
							        // kill_the_process();//this will kill the running process launched by script
							        // die();
							    // }
							    // // $task_completed = true; //true if the task completed
							    // sleep(1);
							// }						
							// ob_end_clean();
							redirect('');
							break;
						case 'run_with_personal_number':
							// print_r('</br>key: run_with_personal_number </br>');
							// $command = 'jybot ';
							// $this->get_function->addToLog('log.txt', $command);
							// $this->get_function->clearFile('debugfile.txt', 'logs/');
							// print_r('</br>COMMAND: '.$command.'</br>');
							// shell_exec($command);
							// redirect('');
				        	break;
						case 'run_with_order_id':
							// print_r('</br>key: run_with_order_id </br>');
							$environmentList = $_POST['environment'];
							$environment = $environmentList[0];
							// print_r('</br>environment: '.$environment.'</br>');
							$orderId = $_POST['order_id'];
							// print_r('</br>orderId: '.$orderId.'</br>');
							$command = 'start "'.$logName.'" /MIN jybot --include zamowienia --log logs//'.$folderName.'//'.$logName.' --output .//logs//'.$folderName.'//'.$outputFileName.'  --report .//logs//'
								.$folderName.'//'.$reportFileName.' --debugfile .//logs//'.$folderName.'//'.$debugFileName.' --variable idZamowienia:'.$orderId.' --variable SOS_ST:'
								.$environment.' C:\ROBOT\CyfrowyPolsat\CyfrowyPolsat\SOS.tsv 2>&1 &';
							$this->get_function->addToLog('log.txt', $command, $userName);
							// $this->get_function->clearFile('debugfile.txt', 'logs/');
							// print_r('</br>COMMAND: '.$command.'</br>');
							shell_exec($command);						
							redirect('');
							// print_r(shell_exec('ipconfig'));
							// redirect('mainPage');
				        	break;
			        	default: 
		        	}
		        	
		        } else {
		        	 // echo '<br/>elseValue: '.$key.'<br/>';
		        }
		    } 
			
			$data['errors'] = null;
		}
		else {
			// write the errors to the $data array
			// NOTE: this must be done after $form->get()
			$data['errors'] = $this->form->errors;

			// the following variable can be used to get all errors in an associative array
			// might be useful when used with json_encode and AJAX functions:

			// $this->form->error_array;
		}
		$this->load->view('vMainPage', $data);		
	}
}